# coding:utf-8

__author__ = 'carey@akhack.com'

import os
import ftplib

host = ''
username = ''
password = ''


work_dir = "/home/workspace"
remote_base_dir = "/test"


f = ftplib.FTP(host, timeout=3)  # 实例化FTP对象
f.login(username, password)  # 登录


def get_filename():
    """
    遍历目录下所有文件
    :return:
    """
    _filename = os.walk(work_dir)
    result = list()
    for main_dir, subdir, file_name_list in _filename:
        for filename in file_name_list:
            file_path = os.path.join(main_dir, filename)
            result.append(file_path)
    return result


def ftp_upload(file_local):
    """
    以二进制形式上传文件
    :return:
    """
    file_remote = remote_base_dir + file_local.split(work_dir)[1].replace(' ', '')
    remote_dir = os.path.dirname(file_local).split(work_dir)[1].replace(' ', '')
    create_dir(remote_dir=remote_dir)

    bufsize = 1024  # 设置缓冲器大小
    fp = open(file_local, 'rb')
    f.storbinary('STOR ' + file_remote, fp, bufsize)
    fp.close()
    print("[INFO] [download successful: %s]" % file_remote)


def create_dir(remote_dir):
    """
    遍历创建ftp目录
    :param remote_dir:
    :return:
    """
    remote_dir_list = remote_dir.split("/")
    f.cwd(remote_base_dir)
    for d in remote_dir_list:
        if d == '':
            continue
        try:
            f.cwd(d)
        except Exception as e:
            f.mkd(d)
            f.cwd(d)


num = 0
file_list = get_filename()

for file_name in file_list:
    print("[INFO] [num: %s] [local file: %s]" % (num, file_name))
    try:
        ftp_upload(file_local=file_name)
        num += 1
    except Exception as e:
        print("[ERROR] [file: %s,upload error: %s]" % (file_name, e))

    # if num == 100:
    #     break

f.quit()
